<template>
  <div id="app" class="main-container">
    <!-- 仪表盘区域 -->
    <div class="dashboard-section">
      <Dashboard />
    </div>
    <!-- 统计页面区域 -->
    <div class="statistics-section">
      <div class="chart-container">
        <div ref="chartRef" class="chart"></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import Dashboard from "@/components/home/Dashboard.vue";
// 在script setup顶部添加引用
import { onMounted, ref, reactive, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';
import { get_products } from '@/api/products';

// 创建一个ref来引用图表容器
const chartRef = ref(null);

// 定义响应式数据
const date = reactive({
  isFirst: true,
  data: [],
  Products: [],
  loading: false,
  key: "",
  details_key: "",
  details_key_id: "",
  pages: {
    page: 1,
    limit: 10,
    total: 0,
  },
  time1: "",
  time2: ""
});

interface Product {
  id: string;
  name: string;
  price: number;
  datetime: string;
  img: string;
  expalain: string;
  list: number;
  enddatetime: string;
  startdatetime: string;
  discountprice: number;
  salesvolume: number;
}

const productsData = ref<Product[]>([]);

// 添加定时器引用和自动刷新逻辑
const chartTimer = ref<NodeJS.Timeout>();
const myChart = ref<echarts.ECharts>();

// 修改fetchTypes方法
const fetchTypes = async () => {
  date.loading = true;
  try {
    const res2 = await get_products({ key: "" });
    if (res2.code === 0) {
      productsData.value = res2.data.data;
      updateChart(); // 数据更新后刷新图表
    }
  } catch (error) {
    console.error('获取类型失败:', error);
    ElMessage.error('获取类型失败');
  } finally {
    date.loading = false;
  }
};

// 新增更新图表方法
const updateChart = () => {
  if (!myChart.value) return;

  // 添加排序和筛选逻辑
  const sortedData = generateDataFromProducts(productsData.value)
    .sort((a, b) => b.value - a.value)  // 改为降序排列
    .slice(0, 5);                       // 取前五条数据

  myChart.value.setOption({
    title: {
      text: '产品销量TOP5'
    },
    tooltip: {},
    legend: {
      data: ['销量']
    },
    xAxis: {
      type: 'category',
      data: sortedData.map(item => item.name)
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      name: '销量',
      type: 'bar',
      data: sortedData.map(item => item.value) // 使用筛选后的数据
    }]
  });
};

// 修改初始化方法
onMounted(() => {
  myChart.value = echarts.init(chartRef.value);
  // 初始化时立即设置一次完整配置
  updateChart();
  // 初始化定时器
  chartTimer.value = setInterval(fetchTypes, 30000);
});

// 添加卸载清理
onUnmounted(() => {
  if (chartTimer.value) clearInterval(chartTimer.value);
  if (myChart.value) {
    window.removeEventListener('resize', myChart.value.resize);
    myChart.value.dispose();
  }
});

fetchTypes();

// 初始化图表
const initChart = () => {
  // 获取DOM元素
  const chartDom = chartRef.value;
  if (!chartDom) return;

  // 初始化ECharts实例
  const myChart = echarts.init(chartDom);

  // 确保数据已经加载完成
  if (productsData.value.length === 0) {
    setTimeout(() => {
      initChart();
    }, 100); // 延迟一段时间确保数据加载完成
    return;
  }

  // 生成并排序数据
  const initialData = generateDataFromProducts(productsData.value).sort((a, b) => a.value - b.value);

  // 配置项和数据
  const option = {
    title: {
      text: '产品销量'
    },
    tooltip: {},
    legend: {
      data: ['销量']
    },
    xAxis: {
      data: initialData.map(item => item.name)
    },
    yAxis: {},
    series: [{
      name: '销量',
      type: 'bar',
      data: initialData.map(item => item.value)
    }]
  };

  // 使用刚指定的配置项和数据显示图表。
  myChart.setOption(option);

  window.addEventListener('resize', () => {
    myChart.resize();
  });
};

// 根据productsData生成图表所需的数据格式
function generateDataFromProducts(products: Product[]) {
  return products.map(product => ({
    name: product.name,
    value: product.salesvolume
  }));
}
</script>

<style scoped>
.main-container {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  padding: 20px;
}

.dashboard-section {
  padding: 18px;
  margin-bottom: 20px;
}

.statistics-section {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.chart-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.chart {
  flex: 1;
  min-width: 300px;
  height: 400px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 10px;
}
</style>
